from rest_framework import mixins, viewsets
from api.models import Product, ProductFormula
from api.serializers import ProductSerializer, ProductListSerializer, ProductFormulaSerializer
from api.filters import ProductFilter, ProductFormulaFilter
from api.utils.Pageination import AppNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter

class ProductViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filterset_class = ProductFilter
    search_fields = ['product_name']
    ordering_fields = ["product_id"]
    ordering = ('product_id',)


class ProductListViewSet(
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = Product.objects.all()
    serializer_class = ProductListSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filterset_class = ProductFilter
    pagination_class = AppNumberPagination # 分页功能
    search_fields = ['product_name']
    ordering_fields = ["product_id"]
    ordering = ('product_id',)
    

class ProductFormulaViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = ProductFormula.objects.all().distinct() # 数据库总查询，可自定义
    serializer_class = ProductFormulaSerializer # 前端自定义Json序列化Class
    filter_backends = [SearchFilter, DjangoFilterBackend, OrderingFilter]  # 参数查询需要的插件支持
    search_fields = ['material_name'] # 模糊查询功能
    filterset_class = ProductFormulaFilter # 参数查询功能
    pagination_class = AppNumberPagination # 分页功能
    ordering_fields = ["id"] # 使用URL排序根据设定字段排序
    ordering = ('-id',) # 不使用URL参数查询时使用设定字段默认排序为降序